package com.yuri.news.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.yuri.news.domain.Result;
import com.yuri.news.entity.Menu;
import com.yuri.news.entity.PrivilegePack;
import com.yuri.news.entity.User;
import com.yuri.news.service.UserService;
//允许跨域访问
@CrossOrigin
//控制器
@Controller
//以json形式返回
@ResponseBody
public class LoginController {
	private final Logger logger =  LoggerFactory.getLogger(LoginController.class);
	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;
	@Autowired
	UserService userService;
	@Autowired
	PrivilegeController privilegeController;
	
	@Autowired
    private RestTemplate restTemplate;
	@Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
	
	 @Value("${back}")
	 String back;
	/**
	 * 用户登录请求
	 * @param userName	登录名
	 * @param userPw	登陆密码
	 * @return
	 */
	@RequestMapping(value = "login")
	public Result<String> login(String userName, String userPw){
		logger.info("\n 登录验证（login）开始 userName=" + userName + "\t userPw = "+userPw);
		Result<String> result = new Result<>();
		try {
			HttpHeaders headers = new HttpHeaders();
	        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
	        MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
	        params.add("grant_type","password");
	        params.add("username",userName);
	        params.add("password",userPw);
	        params.add("scope","select");
	        params.add("client_id","client_2");
	        params.add("client_secret","123456");
	        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
	        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:1011/oauth/token", requestEntity, String.class);
	        String token = response.getBody();
	        
	        JSONObject jsonObject = JSONObject.parseObject(token);
	        String access_token = jsonObject.getString("access_token");
	        System.out.println("token : " + jsonObject.getString("access_token"));
	        MultiValueMap<String, String> params1= new LinkedMultiValueMap<>();
	        params1.add("access_token", access_token);
	        List<String> list = new ArrayList<>();
	        list.add(access_token);
	        result.setData(list);
	        result.setSuccess("查询成功！");
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
        return result;
	}
	
	@RequestMapping(value = "getPack", method = RequestMethod.GET)
	
	public PrivilegePack findPack(User user_){
		logger.info("\n 登录验证（login）开始 user=" + user_ );
		try {
			PrivilegePack userPrivilege = null;
			
			User user = user_;
			if(user != null) {
				// 判断用户是否可用
				if(user.getIsAvailable()) {
					// 查询所有权限
					List<PrivilegePack> privilegePacks = privilegeController.findAuthorAll(true, 0, 1000).getData();
					if(privilegePacks != null)
					// 遍历所有权限
					for(PrivilegePack pack : privilegePacks) {
						// 如果这条权限是属于用户
						if(pack.getUser() != null) {
							// 如果这条权限的用户id与登录id相等
							if(pack.getUser().getId() == user.getId()) {
								userPrivilege = pack;
								break;
							}
						}
					}
					return userPrivilege;
				}else {
					//result.setError("用户被禁用！请联系管理员");
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		//logger.info("\n 登录验证（login）结束result=" + result);
		return null;
	}
	
	
	/**
	 * 获取用户登录信息
	 * @return
	 */
	@RequestMapping(value = "obtainUser", method = RequestMethod.POST)
	public Result<User> obtainUser() {
		logger.info("\n 获取用户登录信息（obtainUser）开始 ");
		
		Result<User> result = new Result<>();
		try {
			List<User> users = new ArrayList<>();
			// 获取用户信息
			User user = (User)request.getSession().getAttribute("user");
			
			if(user != null) {
				users.add(user);
				result.setData(users);
				result.setSuccess("获取成功！");
				
				// 获取用户权限信息
				PrivilegePack userPrivilege = (PrivilegePack)request.getSession().getAttribute("author");
				// 权限不为空   且有菜单权限
				if(userPrivilege != null && userPrivilege.getMenus() != null) {
					// 遍历他的菜单权限
					for(Menu menu : userPrivilege.getMenus()) {
						// 如果有后台管理权限  则设置返回code为2
						System.out.println("back = " + back);
						if(back.equals(menu.getMenuName())) {
							result.setCode(2);
							break;
						}
					}
				}
			}else {
				result.setError("获取失败！用户未登录");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		logger.info("\n 获取用户登录信息（obtainUser）结束 result =  " + result);
		return result;
	}
	
	/**
	 * 获取用户权限信息
	 * @return
	 */
	@RequestMapping(value = "findAuthor", method = RequestMethod.POST)
	public Result<PrivilegePack> findAuthor(){
		logger.info("\n 获取用户权限信息开始");
		Result<PrivilegePack> result = new Result<>();
		try {
			// 获取登录的用户权限信息
			List<PrivilegePack> packs = new ArrayList<>();
			PrivilegePack userPack = (PrivilegePack)request.getSession().getAttribute("author");
			packs.add(userPack);
			
			result.setData(packs);
			result.setSuccess("获取成功！");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		logger.info("\n 获取用户权限信息结束result = "+result);
		return result;
	}
	
	/***
	 * 用户注销
	 */
	@RequestMapping(value = "logout", method = RequestMethod.POST)
	public void logout() {
		// 清空用户信息
		request.getSession().removeAttribute("user");
		// 清空权限信息
		request.getSession().removeAttribute("author");
	}
	
	/**
	 * 跳转主页面
	 */
	@RequestMapping(value = "/")
	public void index() {
		try {
			response.sendRedirect(request.getContextPath() + "/fore-end/index.html");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

